<template>
  <div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>发送站内信</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题"/>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              :rows="6"
              placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sendMessage" :loading="loading">
            发送消息
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { createSite_message } from '@/api/system/site_message'
import { ElMessage } from 'element-plus'

const formRef = ref()
const loading = ref(false)

const form = ref({
  title: '',
  content: '',
  is_read: '0'
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

const sendMessage = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    const res = await createSite_message(form.value)
    if (res.code === 0) {
      ElMessage.success('发送成功')
      resetForm()
    } else {
      ElMessage.error(res.msg || '发送失败')
    }
  } catch (error) {
    ElMessage.error('发送失败')
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    title: '',
    content: '',
    is_read: '0'
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>